package zhuyouyong.bottomtab

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.core.view.marginBottom
import androidx.core.view.marginEnd
import androidx.core.view.marginStart
import androidx.core.view.marginTop

/**
 * @author zhuyouyong <zhuyouyong@hangsheng.com.cn>
 * Created on 2021/5/7.
 */
@Suppress("MemberVisibilityCanBePrivate")
abstract class CustomLayout(context: Context, attrs: AttributeSet? = null) :
    ViewGroup(context, attrs) {
    lateinit var items: Array<View>
    abstract fun setContent(vararg contents: Pair<String, Int>)
    abstract fun setClickListener(click: (Int) -> Unit)
    abstract fun getCurrentPos(): Int

    protected class LayoutParams(width: Int, height: Int) : MarginLayoutParams(width, height)

    protected val Int.dp: Int get() = (this * resources.displayMetrics.density + 0.5f).toInt()

    protected fun Int.toAtMostMeasureSpec(): Int =
        MeasureSpec.makeMeasureSpec(this, MeasureSpec.AT_MOST)

    protected fun Int.toExactlyMeasureSpec(): Int =
        MeasureSpec.makeMeasureSpec(this, MeasureSpec.EXACTLY)

    protected fun View.defaultHeightMeasureSpec(parentView: ViewGroup): Int =
        when (layoutParams.height) {
            ViewGroup.LayoutParams.MATCH_PARENT -> parentView.measuredHeight.toExactlyMeasureSpec()
            ViewGroup.LayoutParams.WRAP_CONTENT -> parentView.measuredHeight.toAtMostMeasureSpec()
            else -> layoutParams.height.toExactlyMeasureSpec()
        }

    protected fun View.defaultWidthMeasureSpec(parentView: ViewGroup): Int =
        when (layoutParams.width) {
            ViewGroup.LayoutParams.MATCH_PARENT -> parentView.measuredWidth.toExactlyMeasureSpec()
            ViewGroup.LayoutParams.WRAP_CONTENT -> parentView.measuredWidth.toAtMostMeasureSpec()
            else -> layoutParams.width.toExactlyMeasureSpec()
        }

    protected val View.measuredHeightWithMargins get() = measuredHeight + marginTop + marginBottom
    protected val View.measuredWidthWithMargins get() = measuredWidth + marginStart + marginEnd

    protected fun View.layout(x: Int, y: Int, fromEnd: Boolean = false) {
        if (!fromEnd) {
            layout(x, y, x + measuredWidth, y + measuredHeight)
        } else {
            layout(this@CustomLayout.measuredWidth - x - measuredWidth, y)
        }
    }

    protected fun View.autoMeasure() = measure(
        defaultWidthMeasureSpec(this@CustomLayout),
        defaultHeightMeasureSpec(this@CustomLayout)
    )
}